package com.hnx.admin.aurora.core;

import com.hnx.admin.aurora.core.api.SqlBuilder;

import java.util.*;

/*
创建人： 倔强的头发
创建时间：2025/7/4
功能描述:

*/
public class SafeInsertSqlBuilder implements SqlBuilder {
    private String table;
    private final StringBuilder sql = new StringBuilder();
    private final Map<String,Object> values = new HashMap<>();
    public SafeInsertSqlBuilder into (String table){
        this.table = table;
        return this;
    }
    public SafeInsertSqlBuilder value(String column,Object value){
        values.put(column,value);
        return this;
    }
    public SafeInsertSqlBuilder valueExpression(String column,String express){
        values.put(column,new ExpressionValue(express));
        return this;
    }
    public SqlWithParams build(){
        if(table == null || table.isEmpty()){
            throw new RuntimeException("表名不能为空");
        }
        if(Objects.isNull(values)){
            throw new RuntimeException("参数值不能为空");
        }
        sql.append("insert into ").append(table).append("(");
        List<String> columns = new ArrayList<>(values.keySet());
        sql.append(String.join(COMMA,columns));
        sql.append(") values (");
        List<String> placeholders = new ArrayList<>();
        List<Object> params = new ArrayList<>();
        for(String column :columns){
            Object value = values.get(column);
            if(value instanceof ExpressionValue){
                placeholders.add(((ExpressionValue) value).expression);
            }
            else{
                placeholders.add(QUESTION);
                params.add(value);
            }

        }
        sql.append(String.join(COMMA,placeholders));
        sql.append(RIGHT);
        return new SqlWithParams(sql.toString(),params.toArray());
    }
    @Override
    public String getSql() {
        return sql.toString();
    }


}
